package com.glodon.ggzy.core.utils;

import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.map.LinkedMap;

/**
 * 
 * 
 * 常用工具处理类
 * @author yangjf
 * @since jdk1.6
 * @date 2013-6-17
 *
 */
public class Tools {

	/**
	 * 对象转换
	 * 
	 * @param object
	 * @return
	 */
	public static int null2Int(Object object) {
		int ivalue = 0;
		ivalue = Integer.parseInt(object.toString());
		return ivalue;
	}

	/**
	 * 获取当前日期 
	 * 
	 * @return 字符串
	 */
	public static String getNowDate() {
		String newTime = "";
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		try {
			newTime = df.format(System.currentTimeMillis());
			return newTime;
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}

	/**
	 * 获取当前时间
	 * 
	 * @return 字符串
	 */
	public static String getNowTime() {
		String newTime = "";
		SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
		try {
			newTime = df.format(System.currentTimeMillis());
			return newTime;
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}

	/**
	 * 获取当前日期和时间
	 * 
	 * @return 字符串
	 */
	public static String getNowDateTime() {
		String newTime = "";
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			newTime = df.format(System.currentTimeMillis());
			return newTime;
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}

	/**
	 * 得到当前时间yyyy-mm-dd HH:mm:ss
	 * 
	 * @return DATE 时间类型
	 */
	public static Date getNow() {
		String dd = getNowDateTime();
		return ProcessDate(dd, "yyyy-MM-dd HH:mm:ss");
	}

	public static String DATE_FORMAT_PATTERN_YEAR_MONTH_DAY = "yyyy-MM-dd";

	public static SimpleDateFormat df = new SimpleDateFormat(DATE_FORMAT_PATTERN_YEAR_MONTH_DAY);

	/**
	 * 日期格式化处理
	 * 
	 * @param strDate 字符串型日期
	 * @return
	 */
	public static java.util.Date formatToUtilDate(String strDate) {
		try {
			return df.parse(strDate);
		} catch (ParseException ex) {
			return null;
		}
	}

	/**
	 * 返回某格式的时间字符串
	 * 
	 * @param aDateTimeStr
	 * @param aDateTimeFmtStr
	 * @param aFmSys
	 * @return 字符串
	 */
	public static String ProcessDateTime(String aDateTimeStr, String aDateTimeFmtStr, String aFmSys) {
		String result = "";
		java.sql.Timestamp tsResult = null;
		if (aDateTimeStr == null)
			return null;
		if (!aDateTimeStr.equals("")) {
			java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(aFmSys);
			java.text.ParsePosition pos = new java.text.ParsePosition(0);
			java.util.Date cDate = formatter.parse(aDateTimeStr, pos);
			tsResult = new java.sql.Timestamp(cDate.getTime());
		}
		String fm = aDateTimeFmtStr;
		if (tsResult != null) {
			java.util.Date cDate = new java.util.Date(tsResult.getTime());
			java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(fm);
			String dateString = formatter.format(cDate);
			result = dateString;
		}
		return result;
	}

	/**
	 * 按照格式返回日期
	 * 
	 * @param args DATE 日期格式
	 */
	public static Date ProcessDate(String aDateStr, String aDateFmtStr) {
		SimpleDateFormat smt = new SimpleDateFormat(aDateFmtStr);
		Date ret;
		if (aDateStr == null || aDateStr.equals(""))
			return null;
		try {
			ret = smt.parse(aDateStr);
		} catch (ParseException e) {
			System.out.println(e.getMessage());
			return null;
		}
		return ret;
	}

	/**
	 * 处理日期转换
	 * 
	 * @param aDateStr 字符串类型日期
	 * @return DATE 类型的日期
	 */
	public static Date ProcessDate(String aDateStr) {
		String aDateFmtStr = "yyyy-MM-dd";
		return ProcessDate(aDateStr, aDateFmtStr);
	}

	/**
	 * 格式化DATE类型日期为字符串类型
	 * 
	 * @param vdate
	 * @param fmt
	 * @return 字符串类型
	 */
	public static String formatDateToString(Date vdate, String fmt) {
		if (vdate == null)
			return "";
		else {
			try {
				SimpleDateFormat smt = new SimpleDateFormat(fmt);
				return smt.format(vdate);
			} catch (Exception e) {
				System.out.println(e.getMessage());
				return "";
			}
		}
	}

	/**
	 * 转为yyyy-MM-dd格式
	 * 
	 * @param vdate
	 * @return 字符串
	 */
	public static String formatDateToString(Date vdate) {
		// 默认yyyy-MM-dd
		String fmt = "yyyy-MM-dd";
		return formatDateToString(vdate, fmt);
	}

	/**
	 * 转为yyyyMMdd格式
	 * 
	 * @param vdate
	 * @return 字符串
	 */
	public static String formatDateToStringShort(Date vdate) {
		// 默认yyyyMMdd
		String fmt = "yyyyMMdd";
		return formatDateToString(vdate, fmt);
	}

	/**
	 * converStrToInteger
	 * 
	 * @param value
	 * @return
	 */
	public static Integer converStrToInteger(String value) {
		if (value == null || value.trim().equals("")) {
			return null;
		} else {
			String converValue = value.replace(",", "");
			if (converValue.indexOf(".") > 0) {
				converValue = converValue.substring(0, converValue.indexOf("."));
			}
			return Integer.parseInt(converValue);
		}
	}

	/**
	 * converIntegerToStr
	 * @param value
	 * @return
	 */
	public static String converIntegerToStr(Integer value) {
		if (value == null) {
			return null;
		} else {
			return value.toString();
		}
	}

	/**
	 * diffdates
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static long diffdates(Date date1, Date date2) {
		long result = 0;
		result = date1.getTime() - date2.getTime();
		result = result / 1000 / 60 / 60 / 24;
		return result;
	}

	/**
	 * 字符串日期类型转换为Date日期类型
	 * @param str
	 * @return
	 */
	public static Date strToDate(String str) {
		Date retDate = null;
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			retDate = dateFormat.parse(str);
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return null;
		}
		return retDate;
	}

	/**
	 * 
	 * 时间格式
	 * @param str
	 * @param formatStr
	 * @return
	 */
	public static Date strToDate(String str, String formatStr) {
		Date retDate = null;
		DateFormat dateFormat = new SimpleDateFormat(formatStr);
		try {
			retDate = dateFormat.parse(str);
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return null;
		}
		return retDate;
	}

	/**
	 * 提供精確的加法運算 
	 * @param args
	 */
	public static double add(double v1, double v2) {
		BigDecimal b1 = new BigDecimal(Double.toString(v1));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.add(b2).doubleValue();
	}

	/**
	 * 提供了精確的減法運算   
	 * @param args
	 */
	public static double sub(double v1, double v2) {
		BigDecimal b1 = new BigDecimal(Double.toString(v1));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.subtract(b2).doubleValue();
	}

	/**
	 *  提供了精確的乘法運算   
	 * @param args
	 */
	public static double mul(double v1, double v2) {
		BigDecimal b1 = new BigDecimal(Double.toString(v1));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.multiply(b2).doubleValue();
	}

	/**
	 * 精確到 小數點以後１10位   
	 */
	private static final int DEF_DIV_SCALE = 10;

	/**
	 * 提供了(相對)精確的除法運算，當發生除不儘的情況時，精確到   
	 * 小數點以後１10位   
	 * @param args
	 */
	public static double div(double v1, double v2) {
		return div(v1, v2, DEF_DIV_SCALE);
	}

	/**
	 * 	提供了(相對)精確的除法運算，當發生除不儘的情況時，由scale參數指定   
	 * 精度，以後的數字四捨五入   
	 * @param args   
	 */
	public static double div(double v1, double v2, int scale) {
		if (scale < 0) {
			throw new IllegalArgumentException("The scale must be a positive integer or zero");
		}
		BigDecimal b1 = new BigDecimal(Double.toString(v1));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
	}

	/**
	 * 提供了精確的小數位四捨五入處理   
	 * @param args   
	 */
	public static double round(double v, int scale) {
		if (scale < 0) {
			throw new IllegalArgumentException("The scale must be a positive integer or zero");
		}
		BigDecimal b = new BigDecimal(Double.toString(v));
		BigDecimal one = new BigDecimal("1");
		return b.divide(one, scale, BigDecimal.ROUND_HALF_DOWN).doubleValue();
	}

	/**
	 * 提供金钱格式转换 格式为00.00（小数点后两位）
	 * 
	 * @param aStr
	 * @return
	 */
	@SuppressWarnings("static-access")
	public static String getMoneyString(String aStr) {
		String strResult = "";
		if (!aStr.trim().equals("")) {
			java.text.DecimalFormat formatter = new java.text.DecimalFormat("0.00");
			Double f = new Double(0.00);
			try {
				strResult = formatter.format(f.valueOf(aStr));
			} catch (Exception ex) {
				System.out.println("com.shecc.core.utils.Tools: getMoneyString(\"" + aStr + "\") execute Error!");
			}
		}
		return strResult;
	}

	/**
	 * 提供金钱格式转换 格式为##00.00（小数点后两位）
	 * 
	 * @param aStr
	 * @return
	 */
	@SuppressWarnings("static-access")
	public static String getMoneyString2(String aStr) {
		String strResult = "";
		if (!aStr.trim().equals("")) {
			java.text.DecimalFormat formatter = new java.text.DecimalFormat(",##0.00");
			Double f = new Double(0.00);
			try {
				strResult = formatter.format(f.valueOf(aStr));
			} catch (Exception ex) {
				System.out.println("com.shecc.core.utils.Tools: getMoneyString(\"" + aStr + "\") execute Error!");
			}
		}
		return strResult;
	}

	/**
	 * 提供带有%的百分比格式
	 * 
	 * @param v
	 * @return
	 */
	public static String getPercentage(double v) {
		NumberFormat nf = NumberFormat.getPercentInstance();
		nf.setMaximumFractionDigits(2);
		return nf.format(v);
	}

	/**
	 * 
	 * 在reponse中返回alert信息
	 * @param message
	 * @param response
	 */
	public static void repsonseJsAlert(String message, HttpServletResponse response) {
		try {
			response.setContentType("text/html; charset=utf-8");
			PrintWriter out = response.getWriter();
			out.print("<script language='javascript'> alert('" + message + "');history.back();</script>");
			out.flush();
			out.close();
		} catch (Exception e) {
			return;
		}
	}

	/**
	 * 
	 * 判断不为空
	 * @param o
	 * @return
	 */
	public static boolean notEmpty(Object o) {
		if (o == null) {
			return false;
		}
		if ("".equals(o.toString())) {
			return false;
		}
		return true;
	}
	
	/**
	 * 返回9月<br>
	 * 2012格式的list
	 * 
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	public static String getDateBrStr(String startDate, String endDate) {
		
		Map<String, List<Integer>> map = getList(startDate, endDate);
		List<String> lst = new ArrayList<String>();
		Set<Map.Entry<String, List<Integer>>> set = map.entrySet();
		Iterator<Map.Entry<String, List<Integer>>> it = set.iterator();

		while (it.hasNext()) {
			Map.Entry<String, List<Integer>> ent = it.next();

			String key = ent.getKey();
			List<Integer> values = ent.getValue();

			for (int i = 0; i < values.size(); i++) {
				lst.add("'" + values.get(i) + "月<br>" + key + "',");
			}
		}
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < lst.size(); i++) {
			buf.append(lst.get(i));
		}
		String ret = buf.toString();
		if(ret == null || "".equals(ret.trim())) {
			
		}
		
		
		ret = ret.substring(ret.indexOf("'"), ret.lastIndexOf(","));

		return ret;
	}

	/**
	 * 返回9<br>
	 * 2012格式的list
	 * 
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	public static List<String> getDateBrList(String startDate, String endDate) {
		Map<String, List<Integer>> map = getList(startDate, endDate);
		List<String> lst = new ArrayList<String>();
		Set<Map.Entry<String, List<Integer>>> set = map.entrySet();
		Iterator<Map.Entry<String, List<Integer>>> it = set.iterator();

		while (it.hasNext()) {
			Map.Entry<String, List<Integer>> ent = it.next();

			String key = ent.getKey();
			List<Integer> values = ent.getValue();

			for (int i = 0; i < values.size(); i++) {
				lst.add(values.get(i) + "月<br>" + key);
			}
		}
		return lst;
	}

	/**
	 * 返回2012-9格式的list
	 * 
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	public static List<String> getDateList(String startDate, String endDate) {
		Map<String, List<Integer>> map = getList(startDate, endDate);
		List<String> lst = new ArrayList<String>();
		Set<Map.Entry<String, List<Integer>>> set = map.entrySet();
		Iterator<Map.Entry<String, List<Integer>>> it = set.iterator();

		while (it.hasNext()) {
			Map.Entry<String, List<Integer>> ent = it.next();

			String key = ent.getKey();
			List<Integer> values = ent.getValue();

			for (int i = 0; i < values.size(); i++) {
				int value = values.get(i);
				if (value < 10){
					lst.add(key + "-0" + values.get(i));
				} else {
					lst.add(key + "-" + values.get(i));
				}
				
			}
		}
		return lst;
	}

	public static Map<String, List<Integer>> getList(String startDate,
			String endDate) {
		int startYear = new Integer(startDate.split("-")[0]).intValue();
		int startMon = new Integer(startDate.split("-")[1]).intValue();

		int endYear = new Integer(endDate.split("-")[0]).intValue();
		int endMon = new Integer(endDate.split("-")[1]).intValue();

		Map<String, List<Integer>> map = new LinkedHashMap<String, List<Integer>>();

		List<Integer> lst = null;
		if (startYear == endYear) { // 同一年
			lst = new ArrayList<Integer>();
			for (int i = startMon; i <= endMon; i++) {
				lst.add(i);
			}
			map.put(startYear+"", lst);
		} else {// endYear大于startYear
			for (int i = startYear; i <= endYear; i++) {
				lst = new ArrayList<Integer>();
				if (i == startYear) {
					for (int j = startMon; j <= 12; j++) {
						lst.add(j);
					}
				} else if (i == endYear) {
					for (int j = 1; j <= endMon; j++) {
						lst.add(j);
					}
				} else
					for (int j = 1; j <= 12; j++) {
						lst.add(j);
					}
				map.put(i+"", lst);
			}
		}
		return map;

	}

}
